package security_rule

import (
	error_constants "app/app_src/framework/constant/error"
	security_constants "app/app_src/framework/constant/security"
	web_constants "app/app_src/framework/constant/web"
	"app/app_src/framework/i18n"
	current_subject "app/app_src/framework/security/current/subject"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"

	web_util "app/app_src/framework/util/web"
)

func RequireAdmin(ctx *gin.Context, subject *current_subject.Subject) bool {
	if subject == nil {
		return RequireAuthed(ctx, subject)
	}

	userType := subject.UserType
	if (userType == security_constants.USER_TYPE_ADMIN) ||
		(userType == security_constants.USER_TYPE_SUPER_ADMIN) {
		return true
	}

	request := ctx.Request
	path := request.URL.Path

	// 根据请求信息，决定返回的结果格式
	if strings.HasSuffix(path, web_constants.URL_PREFIX_API) {
		ctx.PureJSON(http.StatusForbidden, gin.H{
			web_constants.JSON_RESULT_ERROR_CODE: error_constants.UNAUTHORIZED_DENIED,
			web_constants.JSON_RESULT_ERROR_MSG:  i18n.T("访问被拒绝！"),
		})
	} else {
		web_util.HTML(ctx, http.StatusForbidden, "error/403", nil)
	}

	return false
}
